<template>
  <div class="my-purchases-page">
    <!-- 页面头部 -->
    <van-nav-bar 
      title="我买到的" 
      left-arrow 
      @click-left="goBack" 
    />
    
    <!-- 订单类型切换 -->
    <van-tabs v-model:active="activeTab" sticky>
      <van-tab title="全部" name="all">
        <order-list :orders="allOrders" :loading="loading" />
      </van-tab>
      <van-tab title="积分订单" name="points">
        <order-list :orders="pointsOrders" :loading="loading" />
      </van-tab>
      <van-tab title="二手订单" name="vip">
        <order-list :orders="vipOrders" :loading="loading" />
      </van-tab>
      <van-tab title="普通订单" name="normal">
        <order-list :orders="normalOrders" :loading="loading" />
      </van-tab>
    </van-tabs>
    
    <!-- 空状态 -->
    <van-empty 
      v-if="!loading && currentOrders.length === 0"
      description="暂无购买记录"
      image="search"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import OrderList from './components/order-list.vue'
import { getMyPurchases } from '@/api/order'

const router = useRouter()

// 响应式数据
const activeTab = ref('all')
const loading = ref(false)
const allOrders = ref([])

// 计算属性
const pointsOrders = computed(() => 
  allOrders.value.filter(order => order.type === 'points')
)

const vipOrders = computed(() => 
  allOrders.value.filter(order => order.type === 'vip' && order.status === 'confirmed')
)

const normalOrders = computed(() => 
  allOrders.value.filter(order => order.type === 'normal' && order.status === 'paid')
)

const currentOrders = computed(() => {
  switch (activeTab.value) {
    case 'points':
      return pointsOrders.value
    case 'vip':
      return vipOrders.value
    case 'normal':
      return normalOrders.value
    default:
      return allOrders.value
  }
})

// 返回上一页
const goBack = () => {
  router.back()
}

// 加载购买记录
const loadPurchases = async () => {
  loading.value = true
  try {
    const response = await getMyPurchases()
    if (response.success) {
      allOrders.value = response.data || []
    } else {
      showToast(response.message || '加载失败')
    }
  } catch (error) {
    console.error('加载购买记录失败:', error)
    showToast('加载失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadPurchases()
})
</script>

<style lang="scss" scoped>
.my-purchases-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  
  .van-tabs {
    background: #fff;
  }
  
  .van-empty {
    margin-top: 100px;
  }
}
</style> 